import { FC } from "react";
import { Link } from "react-router-dom";

type IFruit = {
  id: number;
  name: string;
};

const fruits = [
  { id: 1, name: "苹果" },
  { id: 2, name: "香蕉" },
  { id: 3, name: "橘子" },
];

/**
 * search 传递路由参数
 *  1. to 直接拼接字符串
 *  2. to 传递对象，且设置 pathname 与 search 字段
 */
const ItemOne: FC<{ fruit: IFruit }> = ({ fruit }) => {
  return (
    <li>
      {/* 1. to 直接拼接字符串 */}
      {/* <Link to={`/info?id=${fruit.id}&name=${fruit.name}`}>{fruit.name}</Link> */}

      {/* 2. to 传递对象，且设置 pathname 与 search 字段 */}
      <Link
        to={{ pathname: "/info", search: `id=${fruit.id}&name=${fruit.name}` }}
      >
        {fruit.name}
      </Link>
    </li>
  );
};

/**
 * params 传递路由参数
 *
 *  1. to 直接拼接字符串
 *  2. to 传递对象，且设置 pathname ， pathname 来做拼接
 */
const ItemTwo: FC<{ fruit: IFruit }> = ({ fruit }) => {
  return (
    <li>
      {/* 1. to 直接拼接字符串 */}
      {/* <Link to={`/info/${fruit.id}/${fruit.name}`}>{fruit.name}</Link> */}

      {/* 2. to 传递对象，且设置 pathname ， pathname 来做拼接 */}
      <Link
        to={{
          pathname: `/info/${fruit.id}/${fruit.name}`,
        }}
      >
        {fruit.name}
      </Link>
    </li>
  );
};

/**
 * state 传递路由参数
 *  1. 只能通过对象的放置，设置好 pathname 与  state
 */
const ItemThree: FC<{ fruit: IFruit }> = ({ fruit }) => {
  return (
    <li>
      <Link
        to={{
          pathname: "/info",
          state: {
            id: fruit.id,
            name: fruit.name,
          },
        }}
      >
        {fruit.name}
      </Link>
    </li>
  );
};

function List() {
  return (
    <ul>
      {fruits.map((item) => (
        // <ItemOne key={item.id} fruit={item} />

        // <ItemTwo key={item.id} fruit={item} />

        <ItemThree key={item.id} fruit={item} />
      ))}
    </ul>
  );
}

export default List;
